<template>
  <div class="events-view">
    <h1>🎭 活动管理</h1>

    <el-card class="toolbar-card" shadow="always">
      <div class="toolbar">
        <el-input v-model="query.keyword" placeholder="关键词（标题/场馆/地址）" clearable class="w-300" @keyup.enter.native="loadEvents" />
        <el-select v-model="query.sortBy" placeholder="排序字段" class="w-160" @change="loadEvents">
          <el-option label="开始时间" value="startTime" />
          <el-option label="标题" value="title" />
          <el-option label="创建时间" value="createdAt" />
          <el-option label="状态" value="status" />
          <el-option label="最低价" value="lowestPrice" />
          <el-option label="热度" value="popularity" />
        </el-select>
        <el-select v-model="query.order" placeholder="顺序" class="w-120" @change="loadEvents">
          <el-option label="升序" value="ASC" />
          <el-option label="降序" value="DESC" />
        </el-select>
        <el-select v-model="query.size" placeholder="每页" class="w-120" @change="handleSizeChange">
          <el-option :value="6" label="每页6条" />
          <el-option :value="12" label="每页12条" />
          <el-option :value="24" label="每页24条" />
        </el-select>
        <el-button type="primary" @click="loadEvents" :loading="loading">查询</el-button>
        <el-button @click="resetFilters" :disabled="loading">重置</el-button>
        <el-button type="success" @click="openCreate">新增活动</el-button>
      </div>
    </el-card>

    <el-card class="table-card" shadow="never">
      <el-table :data="events" border stripe v-loading="loading" style="width: 100%" :max-height="600">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column label="海报" width="100">
          <template #default="{ row }">
            <img :src="row.posterUrl ? `${BASE_URL}${row.posterUrl}` : `${BASE_URL}/images/phantom-opera.svg`" alt="poster" class="poster" />
          </template>
        </el-table-column>
        <el-table-column prop="title" label="标题" min-width="180" />
        <el-table-column prop="venue" label="场馆" min-width="160" />
        <el-table-column prop="category" label="分类" width="120" />
        <el-table-column prop="startTime" label="开始时间" min-width="160">
          <template #default="{ row }">
            {{ formatDate(row.startTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="lowestPrice" label="最低价" width="100">
          <template #default="{ row }">
            <span>¥{{ row.lowestPrice ?? 0 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="(row.status === 1 || row.status === 'OPEN') ? 'success' : (row.status === 0 || row.status === 'CLOSED') ? 'info' : 'warning'">
              {{ formatStatus(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240">
          <template #default="{ row }">
            <el-button size="small" @click="viewEvent(row)">查看</el-button>
            <el-button size="small" type="primary" @click="editEvent(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="removeEvent(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="table-footer">
        <el-pagination
          background
          layout="total, prev, pager, next"
          :total="total"
          :page-size="query.size"
          :current-page="query.page + 1"
          @current-change="handlePageChange"
        />
      </div>
    </el-card>
    
    <!-- 新增/编辑弹窗 -->
    <el-dialog v-model="dialogVisible" :title="isEdit ? '编辑活动' : '新增活动'" width="600">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="100px">
        <el-form-item label="标题" prop="title"><el-input v-model="form.title" /></el-form-item>
        <el-form-item label="场馆" prop="venue"><el-input v-model="form.venue" /></el-form-item>
        <el-form-item label="分类" prop="category"><el-input v-model="form.category" /></el-form-item>
        <el-form-item label="开始时间" prop="startTime"><el-date-picker v-model="form.startTime" type="datetime" placeholder="选择开始时间" /></el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" :loading="saving" @click="submitEvent">保存</el-button>
      </template>
    </el-dialog>
  </div>
  
  <!-- 预留：编辑弹窗（后续实现） -->
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { eventAPI } from '@/api'
import { BASE_URL } from '@/utils/request'

const loading = ref(false)
const router = useRouter()
const events = ref([])
const total = ref(0)
const query = ref({
  page: 0,
  size: 12,
  sortBy: 'startTime',
  order: 'ASC',
  keyword: ''
})

// 编辑弹窗
const dialogVisible = ref(false)
const isEdit = ref(false)
const saving = ref(false)
const formRef = ref(null)
const form = ref({ id: null, title: '', venue: '', category: '', startTime: '' })
const rules = {
  title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
  venue: [{ required: true, message: '请输入场馆', trigger: 'blur' }],
  category: [{ required: true, message: '请输入分类', trigger: 'blur' }],
  startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }]
}

function formatDate(dt) {
  if (!dt) return ''
  const d = new Date(dt)
  return d.toLocaleString('zh-CN')
}

function formatStatus(s) {
  if (s === 1 || s === 'OPEN') return '开放'
  if (s === 0 || s === 'CLOSED') return '关闭'
  if (s === 'CANCELLED') return '已取消'
  if (s === 'DRAFT') return '草稿'
  return String(s ?? '未知')
}



async function loadEvents() {
  try {
    loading.value = true
    const params = { ...query.value }
    const resp = await eventAPI.getEventList(params)
    // 兼容后端分页结构：{ content, totalElements, totalPages }
    const content = resp?.data?.content || resp?.content || []
    events.value = content
    total.value = resp?.data?.totalElements ?? resp?.totalElements ?? content.length
  } catch (err) {
    ElMessage.error(`加载活动失败：${err?.message || '请求错误'}`)
  } finally {
    loading.value = false
  }
}

function resetFilters() {
  query.value = { page: 0, size: 12, sortBy: 'startTime', order: 'ASC', keyword: '' }
  loadEvents()
}

function handleSizeChange() {
  query.value.page = 0
  loadEvents()
}

function handlePageChange(p) {
  query.value.page = p - 1
  loadEvents()
}

function viewEvent(row) {
  router.push(`/events/${row.id}`)
}

function editEvent(row) {
  isEdit.value = true
  form.value = { id: row.id, title: row.title, venue: row.venue, category: row.category, startTime: row.startTime }
  dialogVisible.value = true
}

function openCreate() {
  isEdit.value = false
  form.value = { id: null, title: '', venue: '', category: '', startTime: '' }
  dialogVisible.value = true
}

async function submitEvent() {
  try {
    await formRef.value.validate()
    saving.value = true
    if (isEdit.value && form.value.id) {
      await eventAPI.updateEvent(form.value.id, { ...form.value })
      ElMessage.success('活动已更新')
    } else {
      await eventAPI.createEvent({ ...form.value })
      ElMessage.success('活动已创建')
    }
    dialogVisible.value = false
    loadEvents()
  } catch (err) {
    ElMessage.error(err?.message || '保存失败')
  } finally {
    saving.value = false
  }
}

async function removeEvent(row) {
  try {
    await ElMessageBox.confirm(`确认删除活动「${row.title}」吗？`, '提示', { type: 'warning' })
    await eventAPI.deleteEvent(row.id)
    ElMessage.success('已删除')
    loadEvents()
  } catch (err) {
    if (String(err).includes('cancel')) return
    ElMessage.error(err?.message || '删除失败')
  }
}

onMounted(loadEvents)
onMounted(() => {
  // 读设置默认项
  try {
    const raw = localStorage.getItem('admin_settings')
    if (raw) {
      const s = JSON.parse(raw)
      if (s.pageSize) query.value.size = s.pageSize
      if (s.eventSortBy) query.value.sortBy = s.eventSortBy
      if (s.eventOrder) query.value.order = s.eventOrder
    }
  } catch (_) {}
})
</script>

<style scoped>
.events-view {
  padding: 20px;
}
.toolbar-card {
  margin-bottom: 12px;
}
.toolbar {
  display: flex;
  gap: 12px;
  align-items: center;
}
.w-300 { width: 300px; }
.w-160 { width: 160px; }
.w-120 { width: 120px; }

.poster {
  width: 60px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
}
.table-footer {
  display: flex;
  justify-content: flex-end;
  padding: 12px 0 0;
}
</style>